﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;
using NetMicro.Core.ApiFunction;
using NetMicro.Core.ConfigureOptions;
using NetMicro.Core.Extensions;
using NetMicro.Core.Helper;

namespace NetMicro.JwtBearer
{
    /// <summary>
    /// jwt扩展
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 添加Jwt认证
        /// </summary>
        /// <param name="services"></param>
        public static IServiceCollection AddJwt(this IServiceCollection services, Action<AuthenticationOptions> authenticationConfigure = null, Action<JwtBearerOptions> jwtBearerConfigure = null)
        {
            services.AddConfigure<JWTSettingsOptions>();
            services.AddSingleton<IJwtHandler, JwtHandler>();
            var jwtSetings = App.GetConfig<JWTSettingsOptions>("JWTSettings", true);
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                // 添加自定义配置
                authenticationConfigure?.Invoke(options);
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = jwtSetings.CreateTokenValidationParameters();
                options.Events = new JwtBearerEvents
                {
                    OnChallenge = context =>
                    {
                        context.HandleResponse();
                        context.Response.ContentType = "application/json";
                        context.Response.StatusCode = StatusCodes.Status200OK;
                        context.Response.WriteAsync(ServiceResult.Faild(401, "未授权").ToJson());
                        return Task.FromResult(0);
                    }
                };
                // 添加自定义配置
                jwtBearerConfigure?.Invoke(options);
            });
            return services;
        }
    }
}